package 并发.多线程;

/**
 * 三个不同的线程 A、B、C 将会共用一个 Foo 实例。
 * <p>
 * 线程 A 将会调用 first() 方法
 * 线程 B 将会调用 second() 方法
 * 线程 C 将会调用 third() 方法
 * 请设计修改程序，以确保 second() 方法在 first() 方法之后被执行，third() 方法在 second() 方法之后被执行。
 * User: zhaixiaolong Date:2024/1/16 8:54 ProjectName: algorithm Version:
 */
public class 按序打印 {

    // 允许标志
    int signal = 1;

    public synchronized void first() throws InterruptedException {
        while (signal != 1) {
            wait();
        }
        System.out.println("first...");
        signal = 2;
        notifyAll();

    }

    public synchronized void second() throws InterruptedException {
        while (signal != 2) {
            wait();
        }
        System.out.println("second...");
        signal = 3;
        notifyAll();
    }

    public synchronized void third() throws InterruptedException {
        while (signal != 3) {
            wait();
        }
        System.out.println("third...");
        signal = 1;
        notifyAll();
    }

    public static void main(String[] args) {
        按序打印 o = new 按序打印();

        Thread t1 = new Thread(() -> {
            try {
                o.first();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        Thread t2 = new Thread(() -> {
            try {
                o.second();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        Thread t3 = new Thread(() -> {
            try {
                o.third();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        t1.start();t2.start();t3.start();
    }
}
